<template>
  <div>
    <!-- center	是否对头部和底部采用居中布局 -->
    <el-dialog
      center
      :title="info.isAdd ? '添加商品' : '编辑商品'"
      :visible.sync="info.isShow"
    >
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
      <el-form :model="menuForm" :rules="rules" ref="menu">
        <el-form-item
          prop="first_cateid"
          label="一级分类"
          :label-width="formLabelWidth"
        >
          <el-select v-model="menuForm.first_cateid" @change="firstChange" placeholder="请选择">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="item in firstCateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="second_cateid"
          label="二级分类"
          :label-width="formLabelWidth"
        >
          <el-select v-model="menuForm.second_cateid" placeholder="请选择">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="item in secondCateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="menuForm.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="menuForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" :label-width="formLabelWidth">
          <el-input
            v-model="menuForm.market_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
          ></el-upload>
        </el-form-item>
        <el-form-item
          prop="specsid"
          label="商品规格"
          :label-width="formLabelWidth"
        >
          <el-select v-model="menuForm.specsid" @change="specsChange" placeholder="请选择">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="specsattr"
          label="规格属性值"
          :label-width="formLabelWidth"
        >
          <el-select v-model="menuForm.specsattr" multiple placeholder="请选择">
            <el-option label="请选择" :value="0"></el-option>
            <el-option
              v-for="item in attrList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-switch
            v-model="menuForm.isnew"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-switch
            v-model="menuForm.ishot"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="menuForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      </el-tab-pane>
      <el-tab-pane label="详细描述" name="second">
        <!-- 编辑器所在的容器 -->
        <div id="editor"></div>
      </el-tab-pane>
    </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="info.isAdd" type="primary" @click="submitInfo"
          >添 加</el-button
        >
        <el-button v-else type="primary" @click="submitInfo">编 辑</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入富文本编辑器
import E from 'wangeditor'
//引入封装好的接口
import { getCateList, getSpecsList, getSpecsInfo, goodsEdit, goodsAdd } from "../../util/request/api";
export default {
  props: ["info"],
  data() {
    return {
      // 表单校验的规则
      rules: {
        title: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "长度在 2 到 8 个字符",
            trigger: "blur",
          },
        ],
        pid: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
      },
      formLabelWidth: "120px",
      // 一级分类下拉菜单的数据
      firstCateList: [],
      // 二级分类下拉菜单的数据
      secondCateList: [],
      // 规格名称下拉菜单的数据
      specsList: [],
      // 属性值下拉菜单的数据
      attrList: [],
      // tab标签页默认显示的面板
      activeName: 'first',
      // 富文本编辑器
      editor: null,
      // 表单的数据
      menuForm: {
        first_cateid: 0,
        second_cateid: 0,
        goodsname: '',
        price: '',
        market_price: '',
        img: "",
        description: '',
        specsid: 0,
        specsattr: '',
        isnew: 1,
        ishot: 1,
        status: 1, //状态   1正常2禁用   number类型
      },
    };
  },
  // 使用watch监听属性的变化,在这里用不合适。还是用@change更方便
  // watch: {
  //   menuForm: {
  //     deep: true,
  //     handler(val) {
  //       this.http.get('/rtyukl')
  //     }
  //   }
  // },
  mounted() {
    //页面一加载就调用接口，需要获取一级分类的下拉数据
    this.getFirstList();
    // 获取商品规格的下拉框
    this.getSpecsListFn()
  },
  methods: {
    // 设置表单中的值,给menuForm赋值
    setVal(data) {
      // 解构，为了避免数据互相影响
      this.menuForm = { ...data };
      this.menuForm.specsattr = [1,2]
      // 更新dom是异步的过程，要等待dom更新完成后，isShow等于true之后，不是马上就有弹窗的
      // 等弹窗渲染之后，才会有#editor这个div，然后再初始化编辑器
      this.$nextTick(()=>{
        if(!this.editor) {
          // 初始换的过程，需要判断，如果已经有了一个编辑器，就不用重复创建
          this.editor = new E('#editor');
          this.editor.create();
        }
        this.editor.txt.html(this.menuForm.description);
      })
      // 通过isAdd判断是新增还是修改，如果是修改。需要发getCateList和getSpecsInfo来获取对应下拉框的数据...
    },
    //封装一个获取接口列表的函数
    getFirstList() {
      getCateList({istree: true}).then((res) => {
        if (res.code == 200) {
          this.firstCateList = res.list;
        }
      });
    },
    getSpecsListFn() {
      getSpecsList().then(res => {
        this.specsList = res.list;
      })
    },
    //重置事件
    reset() {
      this.menuForm = {
        first_cateid: 0,
        second_cateid: 0,
        goodsname: '',
        price: '',
        market_price: '',
        img: "",
        description: '',
        specsid: 0,
        specsattr: '',
        isnew: 1,
        ishot: 1,
        status: 1, //状态   1正常2禁用   number类型
      };
    },
    //封装一个取消（关闭弹框）事件
    cancel() {
      this.$emit("cancel", false);
      this.reset();
    },
    //封装一提交事件（包含添加和修改）
    submitInfo() {
      // $refs.menu 查找获取dom节点或者组件
      // validate 校验表单
      this.$refs.menu.validate(async (val) => {
        if (val) {
          // 一级分类的名称和二级分类的名称不应该传给后台，需要删掉
          this.menuForm.firstcatename ? delete this.menuForm.firstcatename : ''
          this.menuForm.secondcatename ? delete this.menuForm.secondcatename : ''
          // editor.txt.html()这个方法可以用来设置或者获取编辑器中的内容
          this.menuForm.description = this.editor.txt.html();
          let fd = new FormData();
          for (const key in this.menuForm) {
            fd.append(key, this.menuForm[key])
          }
          let res = {};
          // 判断新增或修改
          if (this.info.isAdd) {
            res = await goodsAdd(fd);
          } else {
            res = await goodsEdit(fd);
          }
          if (res.code == 200) {
            this.$message.success(res.msg);
            // 通知父组件刷新数据
            this.$emit("update");
            //关闭弹框
            this.cancel();
          } else {
            this.$message.error(res.msg);
          }
        } else {
          console.log(val, "22222");
        }
      });
    },
    // 一级分类变化时，需要获取数据，更新二级分类的选项,是具体的商品 
    firstChange() {
      getCateList({pid: this.menuForm.first_cateid}).then(res => {
        this.secondCateList = res.list;
      })
    },
    // 当属性变换时，需要重新获取属性值的列表
    specsChange() {
      this.menuForm.specsattr = [];
      getSpecsInfo({id: this.menuForm.specsid}).then(res => {
        this.attrList = res.list[0].attrs;
      })
    },
    handleClick() {
      // console.log(tab);
    }
  },
};
</script>

<style scoped></style>
